//
//  MySQLiteTools.m
//  SinaWeibo
//
//  Created by Apple on 16/8/24.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "MySQLiteTools.h"
#import "NativeStatuesModel.h"

@interface MySQLiteTools()

@property (nonatomic, strong) FMDatabase *db;

@end

@implementation MySQLiteTools

+ (instancetype)shareSqliteTools
{
    static MySQLiteTools *tools = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [[MySQLiteTools alloc] init];
    });
    return tools;
}

// 2.定义数据库对象
static FMDatabase *db;
+ (void)initialize
{
    // 0.获取数据库文件地址
    NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"statues.sqlite"];
    
    // 1.创建数据库
    // 如果数据库文件不存在, 就会自动创建文件, 如果存在则不会创建
    db = [FMDatabase databaseWithPath:dbPath];
    
    // 2.打开数据库
    if([db open])
    {
        NSLog(@"success");
        // 2.创建表
        /*
         在FMDB中除了查询以外的操作都称之为更新
         */
        NSString  *sql = @"CREATE TABLE IF NOT EXISTS t_statues(id INTEGER PRIMARY KEY AUTOINCREMENT, dict BLOB, idstr TEXT, access_token TEXT);";
        BOOL success = [db executeUpdate:sql];
        if (success) {
            NSLog(@"create table success---%@",dbPath);
        }else
        {
            NSLog(@"create table error");
        }
        
    }else
    {
        NSLog(@"error");
    }
}

//sqlite只能插入二进制数据

-(BOOL)insertWithDict:(NSDictionary *)dict{
    
    //1.将传入的字典转换为二进制
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    //2.取出字典数据里的idstr
    NSString *idstr = dict[@"idstr"];
    
    AcountModel *acount = [AcountModel acountModelFromSandbox];
 
    return [db executeUpdate:@"INSERT INTO t_statues(dict,idstr,access_token) VALUES(?,?,?)",data,idstr,acount.access_token] ? YES:NO;
    
}

-(NSArray *)getNativeData{
    
    FMResultSet *set = nil;
    
    AcountModel *acount = [AcountModel acountModelFromSandbox];
    
    set = [db executeQuery:@"SELECT * FROM t_statues WHERE access_token = ? ORDER BY idstr DESC LIMIT 99999",acount.access_token];

    
    NSMutableArray *statues = [NSMutableArray array];
    
    while ([set next]) {
        //取出set的data数据
        NSData *statuesData = [set dataForColumn:@"dict"];
        
        //将数据转化为json
        NSDictionary *statuesDict = [NSJSONSerialization JSONObjectWithData:statuesData options:NSJSONReadingMutableContainers error:nil];
        
        StatuesModel *model = [StatuesModel mj_objectWithKeyValues:statuesDict];
        
        [statues addObject:model];
    }
    return statues;
}

@end
